package com.bjc.platform.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.bjc.platform.Constants;
import com.bjc.platform.dao.GenericDao;
import com.bjc.platform.model.AdmOrg;
import com.bjc.platform.model.AdmRole;
import com.bjc.platform.model.AdmUser;
import com.bjc.platform.model.CustomUserDetails;
import com.bjc.platform.repository.AdmUserRepo;
import com.bjc.platform.service.AdmOrgService;
import com.bjc.platform.service.AdmUserService;

public class UserLoginService implements UserDetailsService {

	@Autowired
	@Qualifier("userService")
	private AdmUserService userService;
	@Autowired
	private AdmUserRepo admUserRepo;
	@Autowired
	private AdmOrgService admOrgService;
	@Autowired
	private GenericDao genericDao;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		CustomUserDetails user = new CustomUserDetails();
		
		StringBuilder sql = new StringBuilder();
		sql.append("select url from adm_function where res_id is null or res_id in");
		sql.append("(select res_id from adm_authority where role_id in (-1");

		try {
			AdmUser admUser = userService.findUserByUsername(username);
			if (admUser != null) {
				AdmOrg org = admUser.getOrgnize();				
				user.setId(admUser.getId());
				user.setUsername(admUser.getUsername());
				user.setPassword(admUser.getPassword());
				user.setOrg(org);
				//user.setEmployee(admUser.getEmployee());
				user.setRoles(admUser.getRoles());
				if(org!=null && Constants.ORG_GROUP.equalsIgnoreCase(org.getOrgnizeType())){
					user.setOperCompany(this.admOrgService.getDefaultCompany());
				}
				
				if(user.getRoles() !=  null){
					for(AdmRole role : user.getRoles()){
						sql.append(",").append(role.getId());
					}
				}
				sql.append("))");
				user.setUrlRes(genericDao.queryBySql(sql.toString(),null));
				return user;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

}
